package com.fwtai.dao;

import com.fwtai.bean.AccessToken;
import com.fwtai.bean.RefreshToken;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.stereotype.Repository;

import java.util.Map;

@Repository
public class ApiDao{

  private final JdbcClient jdbcClient;//参考 https://blog.csdn.net/haiyan_qi/article/details/134630536

  public ApiDao(final JdbcClient jdbcClient){
    this.jdbcClient = jdbcClient;
  }

  public int update(final int kid,final String access_token,final String refresh_token){
    return jdbcClient.sql("update token set refresh_time = "+System.currentTimeMillis() / 1000+",access_token = :access_token,refresh_token = :refresh_token where kid = :kid limit 1").param("access_token",access_token).param("refresh_token",refresh_token).param("kid",kid).update();
  }

  public Map<String,Object> getMap(final int kid){
    return jdbcClient.sql("select client_id,client_secret,refresh_token from token where kid = :kid limit 1").param("kid",kid).query().singleRow();
  }

  public RefreshToken queryRefreshToken(final int kid){
    return jdbcClient.sql("select client_id,client_secret,refresh_token from token where kid = :kid limit 1").param("kid",kid).query(RefreshToken.class).single();
  }

  public AccessToken queryAccessToken(final int kid){
    return jdbcClient.sql("select client_id,client_secret from token where kid = :kid limit 1").param("kid",kid).query(AccessToken.class).single();
  }

  public String getRefreshToken(final int kid){
    return jdbcClient.sql("select refresh_token from token where kid = :kid limit 1").param("kid",kid).query(String.class).single();
  }

  public Integer getRefreshTime(final int kid){
    return jdbcClient.sql("select refresh_time from token where kid = :kid limit 1").param("kid",kid).query(Integer.class).single();
  }

  public String getClientId(final int kid){
    return jdbcClient.sql("select client_id from token where kid = :kid limit 1").param("kid",kid).query(String.class).single();
  }

  public Map<String,Object> getInfo(final int kid){
    return jdbcClient.sql("select client_id,client_secret,access_token,folder from token where kid = :kid limit 1").param("kid",kid).query().singleRow();
  }
}